﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using ContentMaintenanceDashboard.Classes;
using ContentMaintenanceDashboard.Helpers;
using umbraco.editorControls;

namespace ContentMaintenanceDashboard
{
    /// <summary>
    /// Responsible for all the UI functionality
    /// </summary>
    public partial class ContentMaintenanceDashboard : System.Web.UI.UserControl
    {
        private pagePicker _parentPicker = new pagePicker();
        private pagePicker _newParentPicker = new pagePicker();

        #region Overrides

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            _parentPicker.ID = "ParentPicker";
            ParentPropertyPlaceHolder.Controls.Add(_parentPicker);

            _newParentPicker.ID = "NewParentPicker";
            NewParentPickerPlaceHolder.Controls.Add(_newParentPicker);

        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            Page.Form.DefaultButton = SearchButton.UniqueID;
            //Initialize dropdown only @ first request
            if (!Page.IsPostBack)
            {
                InitializeDocumentTypeDropdown();
                InitializeStateDropdown();
                InitializeTemplateDropdown();
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            ResultPane.Visible = ShowResult && (OverviewGrid.Rows.Count > 0);
            NoresultPane.Visible = ShowResult && (OverviewGrid.Rows.Count == 0);

            MessageFeedback.Text = FeedBackMessage;
            MessageFeedback.Visible = !string.IsNullOrEmpty(FeedBackMessage);

        }
        #endregion

        #region Event Handlers

       protected  void OverviewGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            OverviewGrid.PageIndex = e.NewPageIndex;
            InitializeResult();
        }

       /// <summary>
       /// Someone clicked sort
       /// </summary>
       protected void OverviewGrid_Sorting(object sender, GridViewSortEventArgs e)
       {
           if (SortExpression != e.SortExpression)
           {
               SetSortExpression(e.SortExpression);
           }
           else
           {
               SortOrder = SortOrder == " ASC " ? " DESC " : " ASC ";
           }
           InitializeResult();
       }

       protected void ParentValidate(object source, ServerValidateEventArgs args)
       {
           int result = 0;
           int.TryParse(_newParentPicker.Value, out result);

           args.IsValid = result != 0;
       }

        protected void SearchButton_Click(object sender, EventArgs e)
        {
            SortExpression = "";
            SortOrder = "";
            OverviewGrid.PageIndex = 0;
            InitializeResult();
        }
        protected void DeleteButton_Command(object sender, CommandEventArgs e)
        {
            UmbracoHelper.DeleteItem(GetCommandArgumentFromSender(sender));
            FeedBackMessage = "Item(s) deleted";
            umbraco.BasePages.BasePage.Current.ClientTools.RefreshTree();
            InitializeResult();
        }
        protected void PublisButton_Command(object sender, CommandEventArgs e)
        {
            UmbracoHelper.PublishItem(GetCommandArgumentFromSender(sender));
            FeedBackMessage = "Item(s) Published";
            umbraco.BasePages.BasePage.Current.ClientTools.RefreshTree();
            InitializeResult();
        }
        protected void UnpublishButton_Command(object sender, CommandEventArgs e)
        {
            UmbracoHelper.UnPublishItem(GetCommandArgumentFromSender(sender));
            FeedBackMessage = "Item(s) Unpublished";
            umbraco.BasePages.BasePage.Current.ClientTools.RefreshTree();
            InitializeResult();
        }

        protected void PublishAllButton_Click(object sender, EventArgs e)
        {
            UmbracoHelper.PublishAll(GetSelectedIds());
            FeedBackMessage = "Item(s) Published";
            umbraco.BasePages.BasePage.Current.ClientTools.RefreshTree();
            InitializeResult();
        }

        protected void UnPublishAllButton_Click(object sender, EventArgs e)
        {
            UmbracoHelper.UnPublishAll(GetSelectedIds());
            FeedBackMessage = "Item(s) Ubpublished";
            umbraco.BasePages.BasePage.Current.ClientTools.RefreshTree();
            InitializeResult();
        }

        protected void DeleteAllButton_Click(object sender, EventArgs e)
        {
            UmbracoHelper.DeleteAll(GetSelectedIds());
            FeedBackMessage = "Item(s) Deleted";
            umbraco.BasePages.BasePage.Current.ClientTools.RefreshTree();
            InitializeResult();
        }

        protected void MoveAllButton_Click(object sender, EventArgs e)
        {
            ShowResult = true;
            ShowMoveOptions();
        }

        protected void CancelMove_Click(object sender, EventArgs e)
        {
            ShowResult = true;
            HideMoveOptions();
        }

        

        protected void DoMoveAllButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                int parent = 0;
                int.TryParse(_newParentPicker.Value, out parent);

                bool result = UmbracoHelper.MoveAll(GetSelectedIds(), parent);

                FeedBackMessage = "Item(s) moved";

                if (!result)
                {
                    FeedBackMessage += "<br/>Note Not all items could be moved because it would result in a parent/child conflict";
                }

                InitializeResult();
                umbraco.BasePages.BasePage.Current.ClientTools.RefreshTree();
            }
            else
            {
                ShowMoveOptions();
            }
        }


        protected void SelectAllButton_Click(object sender, EventArgs e)
        {
            SelectAllItems(true);
        }

        protected void DeSelectAllButton_Click(object sender, EventArgs e)
        {
            SelectAllItems(false);
        }
#endregion

        #region Methods
        private void InitializeDocumentTypeDropdown()
        {
            DocumentTypeDropdown.DataSource = UmbracoHelper.GetAllContentTypes();
            DocumentTypeDropdown.DataTextField = "text";
            DocumentTypeDropdown.DataValueField = "alias";
            DocumentTypeDropdown.Items.Add(EmptyListItem());
            DocumentTypeDropdown.AppendDataBoundItems = true;
            DocumentTypeDropdown.DataBind();
        }

        private void InitializeTemplateDropdown()
        {
            TemplateDropdown.DataSource = UmbracoHelper.GetAllTemplates();
            TemplateDropdown.DataTextField = "text";
            TemplateDropdown.DataValueField = "id";
            TemplateDropdown.Items.Add(EmptyListItem());
            TemplateDropdown.AppendDataBoundItems = true;
            TemplateDropdown.DataBind();
        }

        private void InitializeStateDropdown()
        {
            StateDropdown.Items.Add(EmptyListItem());
            StateDropdown.Items.Add(new ListItem("Published", "true"));
            StateDropdown.Items.Add(new ListItem("UnPublished", "false"));
        }

        private void InitializeResult()
        {
            //Define searchFilter
            SearchFilter searchFilter = new SearchFilter();
            searchFilter.Name = SearchFilterTextBox.Text;
            searchFilter.DocumentType = DocumentTypeDropdown.SelectedValue;
            searchFilter.SearchInContent = SearchInContentCheckBox.Checked;
            searchFilter.Parent = _parentPicker.Value;
            if (TemplateDropdown.SelectedValue != string.Empty)
            {
                searchFilter.Template = int.Parse(TemplateDropdown.SelectedValue);
            }            

            if (StateDropdown.SelectedValue != string.Empty)
            {
                searchFilter.Published = bool.Parse(StateDropdown.SelectedValue);
            }
            
            //Initialize Datagrid
            OverviewGrid.Width = Unit.Percentage(100.00);
            OverviewGrid.PageSize = int.Parse(RecordPerPageDropdown.SelectedValue);
                       
            DataTable dt = DataHelper.GetAllDocuments(searchFilter);
             // Check if a field is selected for siorting, if not sort on th first field
            if (SortExpression == string.Empty)
            {
                SetSortExpression(OverviewGrid.Columns[1].SortExpression);
            }

            dt.DefaultView.Sort = string.Format(" {0} {1}", SortExpression, SortOrder);

            OverviewGrid.DataSource = dt;
            OverviewGrid.DataBind();

            ShowResult = true;

            HideMoveOptions();
        }

        private void SetSortExpression(string column)
        {
            SortExpression = column;
            SortOrder = " ASC ";
        }

      
        private void SelectAllItems(bool select)
        {
            foreach (GridViewRow item in OverviewGrid.Rows)
            {
                ((ValueCheckBox)item.FindControl("SelectCheckbox")).Checked = select;
            }
            ShowResult = true;
        }

        private List<int> GetSelectedIds()
        {
            List<int> result = new List<int>();
            foreach (GridViewRow item in OverviewGrid.Rows)
            {
                ValueCheckBox cb = (ValueCheckBox)item.FindControl("SelectCheckbox");
                if (cb.Checked)
                {
                    result.Add(int.Parse(cb.Value));
                }

            }
            return result;
        }
        private ListItem EmptyListItem()
        {
            return new ListItem("Select", "");
        }

        private int GetCommandArgumentFromSender(object sender)
        {
            Button btn = (Button)sender;
            return int.Parse(btn.CommandArgument);
        }

        private void ShowMoveOptions()
        {
            ShowResult = true;
            MassMoveOptionsPlaceholder.Visible = true;
            MassOptionButtons.Visible = false;
        }

        private void HideMoveOptions()
        {
            MassMoveOptionsPlaceholder.Visible = false;
            MassOptionButtons.Visible = true;
        }


        #endregion

        #region Properties
        private string SortExpression
        {
            get { return string.Format("{0}", ViewState["SortExpression"]); }
            set { ViewState["SortExpression"] = value; }
        }

        private string SortOrder
        {
            get { return string.Format("{0}", ViewState["SortOrder"]); }
            set { ViewState["SortOrder"] = value; }
        }

        public bool ShowResult { get; set; }

        /// <summary>
        /// This message will be shown when an action succeeded
        /// </summary>
        private string FeedBackMessage { get; set; }

        #endregion
    }
}